import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;

public class WarehouseManageFrame extends JFrame {
    private JTable warehouseTable;
    private DefaultTableModel tableModel;

    public WarehouseManageFrame() {
        setTitle("仓位管理");
        setSize(600, 400);
        setLocationRelativeTo(null);

        // 表格模型
        tableModel = new DefaultTableModel();
        tableModel.addColumn("仓位编号");
        tableModel.addColumn("名称");
        tableModel.addColumn("地址");
        tableModel.addColumn("负责人");

        warehouseTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(warehouseTable);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        JButton addBtn = new JButton("添加");
        JButton editBtn = new JButton("修改");
        JButton deleteBtn = new JButton("删除");
        JButton refreshBtn = new JButton("刷新");

        buttonPanel.add(addBtn);
        buttonPanel.add(editBtn);
        buttonPanel.add(deleteBtn);
        buttonPanel.add(refreshBtn);

        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        loadWarehouseData();

        // 事件监听
        addBtn.addActionListener(e -> {
            new WarehouseEditDialog(null).setVisible(true);
            loadWarehouseData();
        });

        editBtn.addActionListener(e -> {
            int selectedRow = warehouseTable.getSelectedRow();
            if (selectedRow >= 0) {
                String wno = (String) tableModel.getValueAt(selectedRow, 0);
                new WarehouseEditDialog(wno).setVisible(true);
                loadWarehouseData();
            } else {
                JOptionPane.showMessageDialog(this, "请选择要修改的行", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        deleteBtn.addActionListener(e -> deleteWarehouse());
        refreshBtn.addActionListener(e -> loadWarehouseData());
    }

    private void loadWarehouseData() {
        tableModel.setRowCount(0);

        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT w.*, s.sname as manager_name FROM warehouse w LEFT JOIN sale s ON w.sno = s.sno")) {

            while (rs.next()) {
                tableModel.addRow(new Object[]{
                        rs.getString("wno"),
                        rs.getString("wname"),
                        rs.getString("waddress"),
                        rs.getString("manager_name") != null ? rs.getString("manager_name") : "未分配"
                });
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void deleteWarehouse() {
        int selectedRow = warehouseTable.getSelectedRow();
        if (selectedRow >= 0) {
            String wno = (String) tableModel.getValueAt(selectedRow, 0);

            int confirm = JOptionPane.showConfirmDialog(
                    this,
                    "确定要删除仓位 " + wno + " 吗?",
                    "确认删除",
                    JOptionPane.YES_NO_OPTION);

            if (confirm == JOptionPane.YES_OPTION) {
                try (Connection conn = DBUtil.getConnection();
                     PreparedStatement pstmt = conn.prepareStatement("DELETE FROM warehouse WHERE wno = ?")) {

                    pstmt.setString(1, wno);
                    int affectedRows = pstmt.executeUpdate();

                    if (affectedRows > 0) {
                        JOptionPane.showMessageDialog(this, "删除成功");
                        loadWarehouseData();
                    }
                } catch (SQLException e) {
                    JOptionPane.showMessageDialog(this, "删除失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要删除的行", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }
}

class WarehouseEditDialog extends JDialog {
    private JTextField wnoField, wnameField, waddressField;
    private JComboBox<String> managerCombo;
    private boolean isEditMode;
    private DefaultComboBoxModel<String> managerModel;

    public WarehouseEditDialog(String wno) {
        if (wno == null) {
            setTitle("添加仓位");
            isEditMode = false;
        } else {
            setTitle("修改仓位");
            isEditMode = true;
        }

        setSize(500, 300);
        setModal(true);
        setLocationRelativeTo(null);

        // 初始化负责人下拉框模型
        managerModel = new DefaultComboBoxModel<>();
        loadManagerData();

        JPanel panel = new JPanel(new GridLayout(4, 2, 5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        panel.add(new JLabel("仓位编号:"));
        wnoField = new JTextField();
        if (isEditMode) wnoField.setEditable(false);
        panel.add(wnoField);

        panel.add(new JLabel("仓位名称:"));
        wnameField = new JTextField();
        panel.add(wnameField);

        panel.add(new JLabel("仓位地址:"));
        waddressField = new JTextField();
        panel.add(waddressField);

        panel.add(new JLabel("负责人:"));
        managerCombo = new JComboBox<>(managerModel);
        managerCombo.insertItemAt("未分配", 0); // 添加"未分配"选项
        managerCombo.setSelectedIndex(0);
        panel.add(managerCombo);

        JButton saveBtn = new JButton("保存");
        saveBtn.addActionListener(e -> saveWarehouse());

        JButton cancelBtn = new JButton("取消");
        cancelBtn.addActionListener(e -> dispose());

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        buttonPanel.add(saveBtn);
        buttonPanel.add(cancelBtn);

        add(panel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        if (isEditMode) {
            loadWarehouseData(wno);
        }
    }

    private void loadManagerData() {
        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT sno, sname FROM sale")) {

            while (rs.next()) {
                managerModel.addElement(rs.getString("sname") + " (" + rs.getString("sno") + ")");
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载负责人数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void loadWarehouseData(String wno) {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(
                     "SELECT w.*, s.sname FROM warehouse w LEFT JOIN sale s ON w.sno = s.sno WHERE w.wno = ?")) {

            pstmt.setString(1, wno);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                wnoField.setText(rs.getString("wno"));
                wnameField.setText(rs.getString("wname"));
                waddressField.setText(rs.getString("waddress"));

                // 设置选中的负责人
                String sno = rs.getString("sno");
                if (sno != null) {
                    String sname = rs.getString("sname");
                    String managerText = sname + " (" + sno + ")";
                    managerCombo.setSelectedItem(managerText);
                } else {
                    managerCombo.setSelectedIndex(0); // 选择"未分配"
                }
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载仓位数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void saveWarehouse() {
        String wno = wnoField.getText().trim();
        String wname = wnameField.getText().trim();
        String waddress = waddressField.getText().trim();
        String managerSelected = (String) managerCombo.getSelectedItem();

        // 从下拉框中提取负责人编号
        String sno = null;
        if (managerSelected != null && !"未分配".equals(managerSelected)) {
            sno = managerSelected.substring(managerSelected.lastIndexOf("(") + 1, managerSelected.lastIndexOf(")"));
        }

        // 验证输入
        if (wno.isEmpty() || wname.isEmpty()) {
            JOptionPane.showMessageDialog(this, "仓位编号和名称不能为空", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try (Connection conn = DBUtil.getConnection()) {
            PreparedStatement pstmt;

            if (isEditMode) {
                pstmt = conn.prepareStatement(
                        "UPDATE warehouse SET wname=?, waddress=?, sno=? WHERE wno=?");
                pstmt.setString(1, wname);
                pstmt.setString(2, waddress);
                pstmt.setString(3, sno);
                pstmt.setString(4, wno);
            } else {
                pstmt = conn.prepareStatement(
                        "INSERT INTO warehouse (wno, wname, waddress, sno) VALUES (?, ?, ?, ?)");
                pstmt.setString(1, wno);
                pstmt.setString(2, wname);
                pstmt.setString(3, waddress);
                pstmt.setString(4, sno);
            }

            int affectedRows = pstmt.executeUpdate();

            if (affectedRows > 0) {
                JOptionPane.showMessageDialog(this, "保存成功");
                dispose();
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "保存失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}